package cn.stylefeng.guns.modular.business.frequency.pricelibrary.listener.excel;

import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.modular.business.frequency.cmcity.mapper.CmCityMapper;
import cn.stylefeng.guns.modular.business.frequency.pricelibrary.entity.PriceLibrary;
import cn.stylefeng.guns.modular.business.frequency.pricelibrary.mapper.PriceLibraryMapper;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 * @Author jzy
 * @Date 2021/10/28
 **/
public class PriceLibraryListener extends AnalysisEventListener<PriceLibrary> {

    public List<PriceLibrary> getDatas() {
        return datas;
    }

    public void setDatas(List<PriceLibrary> datas) {
        this.datas = datas;
    }

    private List<PriceLibrary> datas = new ArrayList<>();
    private static final int BATCH_COUNT = 3000;
    private PriceLibraryMapper priceLibraryMapper;
    private CmCityMapper cmCityMapper;

    public PriceLibraryListener(PriceLibraryMapper priceLibraryMapper, CmCityMapper cmCityMapper) {
        this.priceLibraryMapper = priceLibraryMapper;
        this.cmCityMapper = cmCityMapper;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param priceLibrary    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param analysisContext
     */
    @Override
    public void invoke(PriceLibrary priceLibrary, AnalysisContext analysisContext) {
        datas.add(priceLibrary);
        /*if (datas.size() >= BATCH_COUNT) {
            saveData();
            datas.clear();
        }*/
    }

    private void saveData() {
        for (PriceLibrary data : datas) {
            data.setStatus(1);
            data.setType(1);
            data.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
            data.setCheckUser(LoginContextHolder.me().getSysLoginUserId());
            data.setCheckTime(new Date());
            data.setTotalFee(data.getCost().add(data.getProfit()));
            data.setStartCode(cmCityMapper.getCodeByName(data.getStartCode()));
            data.setDestinationCode(cmCityMapper.getCodeByName(data.getDestinationCode()));
            this.priceLibraryMapper.insert(data);
        }
    }


    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.priceLibraryMapper.delete(new QueryWrapper<PriceLibrary>().lambda().eq(PriceLibrary::getStatus, 1));
        saveData();
    }
}
